//
//  OrderListView.m
//  danpin
//
//  Created by chuangjia on 25/11/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "OrderListView.h"
#import "SVPullToRefreshView+OY_PullRefreshView.h"
#import "viewconfig.h"
#import "NSString+Extensions.h"
#import "OrderListCell.h"
#import "OrderApi.h"
@interface OrderListView ()<UITableViewDataSource,UITableViewDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbview;
@property(nonatomic,strong)NSMutableArray *itemDatas;
@property(nonatomic,assign)int currentPage;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)BOOL isRequesting;
@property(nonatomic,assign)BOOL isRefresh;
@property(nonatomic,assign)float lastOffsetY;
//
@property(nonatomic,assign)BOOL isUseControl;
@end

@implementation OrderListView
@synthesize tbview=_tbview;
@synthesize itemDatas=_itemDatas;
@synthesize currentPage=_currentPage;
@synthesize actionstring=_actionstring;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _lastOffsetY= 0;
        _isUseControl = NO;
        _currentPage= 0;
        if (!_itemDatas) {
            _itemDatas =[[NSMutableArray alloc] init];
        }
        [self initUI];
    }
    return self;
}

-(void)dealloc
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    self.tbview =nil;
    self.itemDatas =nil;
    NSLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)layoutSubviews
{
    [super layoutSubviews];
}
-(void)reloadData
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    self.isRequesting = YES;
    self.isRefresh = YES;
    self.isLoadFinished = NO;
    self.isUseControl = NO;
    self.currentPage= 0;
   
}
-(void)setCallBack:(void(^)(UIView*,id,id,id))callback
{
    self.actionBlock =callback;
}
-(void)initUI
{
    if (_tbview) {
        _tbview.dataSource=nil;
        _tbview.delegate =nil;
        [_tbview removeFromSuperview];
        _tbview=nil;
    }
    _tbview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) style:UITableViewStyleGrouped];
    _tbview.delegate = self;
    _tbview.dataSource = self;
    _tbview.backgroundColor =[UIColor colorWithRed:0.967 green:0.967 blue:0.967 alpha:1];
    _tbview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbview.showsHorizontalScrollIndicator = NO;
    _tbview.showsVerticalScrollIndicator = NO;
    _tbview.scrollsToTop = YES;
    [self addSubview:_tbview];
    
    __weak typeof (self) wSelf = self;
    self.currentPage = 0;
    [_tbview addPullToRefreshWithActionHandler:^{
        wSelf.isRequesting = YES;
        wSelf.isRefresh = YES;
        wSelf.currentPage = 0;
        wSelf.isLoadFinished = NO;
        [wSelf.tbview.pullToRefreshView startAnimating];
        [wSelf  getOrderList];
    }];
    //
    //
    [_tbview.pullToRefreshView setOYStyle];
    
    [_tbview addInfiniteScrollingWithActionHandler:^{
        
        if (wSelf.isRequesting) {
            return;
        }
        if (wSelf.isLoadFinished) {
            if (wSelf.isRefresh) {
                wSelf.isRefresh = NO;
            }
            //停止菊花
            [wSelf.tbview.infiniteScrollingView stopAnimating];
            [wSelf.tbview setShowsInfiniteScrolling:NO];
            return;
        }
        [wSelf.tbview.infiniteScrollingView startAnimating];
        if ([wSelf.itemDatas count]==0) {
            wSelf.currentPage =0;
        }else{
            wSelf.currentPage =(int)[wSelf.itemDatas count] +1;
        }
        
        
        [wSelf  getOrderList];
    }];
    
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.itemDatas.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 5;
    }
    return 15;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [OrderListCell returnCellHeight:nil];
    
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderListCell *cell = (OrderListCell*)[tableView  dequeueReusableCellWithIdentifier:@"OrderListCell"];
    if(cell == nil)
    {
        cell = [[OrderListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"OrderListCell"];//一定要重用啊，否则用户订单多了会卡死的
        cell.backgroundColor=[UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        __weak typeof (self) wSelf = self;
        [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
            [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
        }];
    }
    if (indexPath.section>=self.itemDatas.count)
    {
        return cell;
    }
    
    NSDictionary *dict = [self.itemDatas objectAtIndex:indexPath.section];
    [cell showInfo:dict key:@"OrderListCell" indexPath:indexPath];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section>=self.itemDatas.count) {
        return;
    }
    NSDictionary *dict = [self.itemDatas objectAtIndex:indexPath.section];
    if (self.actionBlock) {
        self.actionBlock(self,dict,@"orderDetail",indexPath);
    }
    
}
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    NSString *status =@"";
    switch (type) {
        case BEventType_help:
        {
            NSDictionary *dict = (NSDictionary*)obj;
            status =[[NSString stringWithFormat:@"%@",[dict objectForKey:@"status"]] replaceNullString];
        }
            break;
        default:
            break;
    }
    if (self.actionBlock) {
        self.actionBlock(self,obj,status,indexPath);
    }
}
//====================================================
//
//====================================================
-(void)getOrderList
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    NSString *status =@"";
    if([_actionstring isEqualToString:@"未付款"])
    {
        status=@"0";
    }else if([_actionstring isEqualToString:@"进行中"])
    {
        status =@"waiting";
    }else if([_actionstring isEqualToString:@"已完成"])
    {
        status=@"9";
    }else if([_actionstring isEqualToString:@"所有订单"])
    {
        status=@"all";
    }
    [dict setValue:status forKey:@"status"];
    [dict setValue:[NSString stringWithFormat:@"%d",_currentPage] forKey:@"from"];
    self.isRequesting =YES;
    __weak typeof (self) wSelf = self;
    [OrderApi getShopOrderList:dict success:^(AFHTTPRequestOperation *operation, id result) {
        [wSelf parserResultObject:result];
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbview.pullToRefreshView stopAnimating];
        [wSelf.tbview.infiniteScrollingView stopAnimating];
        //     [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbview.pullToRefreshView stopAnimating];
        [wSelf.tbview.infiniteScrollingView stopAnimating];
        //     [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
}
-(void)parserResultObject:(id)resultObject
{
    //  [ZShare hiddenAnimationView:self.view];
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]])
    {
        id data =  [resultObject objectForKey:@"data"];
        if (data && [data isKindOfClass:[NSArray class]]){
            if (self.currentPage ==0) {
                [self.itemDatas removeAllObjects];
                self.tbview.tableFooterView =nil;
                [self.tbview setShowsInfiniteScrolling:YES];
            }
            for (NSDictionary *dict in data) {
                [self.itemDatas addObject:dict];
            }
        }
        self.isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
        
        if (self.isLoadFinished)
        {
            [self.tbview.infiniteScrollingView stopAnimating];

            if(self.itemDatas.count==0)
            {
                self.tbview.tableFooterView = [self noData_footerView];
            }else{
                NSString *end_msg =[resultObject objectForKey:@"end_msg"];
                self.tbview.tableFooterView =[ZShare footerView:end_msg];
            }
            [self.tbview setShowsInfiniteScrolling:NO];
            
        }
        else
        {
            if(self.itemDatas.count==0)
            {
                self.tbview.tableFooterView = [self noData_footerView];
            }
        }
    }
    [self.tbview reloadData];
}

-(UIView *)footerView:(NSString*)msg
{
    if (msg==nil || msg.length==0) {
        msg=[ZShare sharedInstance].refreshFooter;
    }
    UIView *footerview =[[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 90)];
    footerview.backgroundColor=[UIColor clearColor];
    UILabel *footLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 20)];
    footLabel.backgroundColor = [UIColor clearColor];
    footLabel.textColor = UIColorFromRGB(0xcccccc);
    footLabel.textAlignment = NSTextAlignmentCenter;
    footLabel.font = FONT(12);
    footLabel.text =msg;
    [footerview addSubview:footLabel];
    return footerview;
}
-(UIView *)noData_footerView
{
    
    UIView *footerview =[[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150)];
    footerview.backgroundColor=[UIColor clearColor];
    UIImage *iconimage =[UIImage imageNamed:@"noorder"];
    UIImageView *icon =[[UIImageView alloc] initWithFrame:CGRectMake((footerview.frame.size.width-iconimage.size.width)/2, 80, iconimage.size.width, iconimage.size.height)];
    icon.image =iconimage;
    [footerview addSubview:icon];
    
    UILabel *titleLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, icon.frame.origin.y+icon.frame.size.height+10, [UIScreen mainScreen].bounds.size.width, 20)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = UIColorFromRGB(0x999999);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = FONT(14);
    if (_actionstring.length>0 && ![_actionstring isEqualToString:@"所有订单"]) {
       titleLabel.text = [NSString stringWithFormat:@"您暂时没有%@订单哦",_actionstring];
    }else{
        titleLabel.text=@"您暂时没有订单哦";
    }
   
    [footerview addSubview:titleLabel];
    
    UILabel *footLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, titleLabel.frame.origin.y+titleLabel.frame.size.height+5, [UIScreen mainScreen].bounds.size.width, 20)];
    footLabel.backgroundColor = [UIColor clearColor];
    footLabel.textColor = UIColorFromRGB(0xcccccc);
    footLabel.textAlignment = NSTextAlignmentCenter;
    footLabel.font = FONT(12);
    footLabel.text=@"快去逛逛吧，全球尖货任您挑";
    [footerview addSubview:footLabel];
    //
    titleLabel=nil;
    footLabel=nil;
    icon=nil;
    return footerview;
}
@end
